package com.mysoft.gfyx.clue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mysoft.framework.common.enums.PromptType;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.user.User;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.core.function.authorization.AuthenticationUser;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.sdk.system.api.MessagePush;
import com.mysoft.framework.sdk.system.dto.MessagePushDTO;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.clue.controller.dto.DeleteByIdRequestDto;
import com.mysoft.gfyx.clue.dao.CustomerDao;
import com.mysoft.gfyx.clue.dao.CustomerPoolCloudDataDao;
import com.mysoft.gfyx.clue.dao.CustomerPoolDao;
import com.mysoft.gfyx.clue.dao.dto.CustomerPoolDataDto;
import com.mysoft.gfyx.clue.dao.dto.CustomerPoolTotalDto;
import com.mysoft.gfyx.clue.dao.entity.Customer;
import com.mysoft.gfyx.clue.dao.entity.CustomerPool;
import com.mysoft.gfyx.clue.dao.entity.CustomerPoolCloudData;
import com.mysoft.gfyx.clue.mip.dto.CustomersPoolRequestDto;
import com.mysoft.gfyx.clue.remoteservice.RemoteDeveloperService;
import com.mysoft.gfyx.clue.remoteservice.RemoteSupplierService;
import com.mysoft.gfyx.clue.remoteservice.dto.CreditCodeBaseRequestDto;
import com.mysoft.gfyx.clue.remoteservice.dto.GetDataByCreditCodeDto;
import com.mysoft.gfyx.clue.service.CustomerPoolService;
import com.mysoft.gfyx.clue.service.MessageInboxService;
import com.mysoft.gfyx.clue.service.NewUserService;
import com.mysoft.gfyx.clue.service.UserBehaviourService;
import com.mysoft.gfyx.clue.service.dto.CustomerPoolDto;
import com.mysoft.gfyx.clue.service.dto.MessageInboxDto;
import com.mysoft.gfyx.common.rpc.openapi.OpenapiClientFactoryService;
import com.mysoft.gfyx.common.rpc.openapi.OpenapiClientService;
import com.mysoft.gfyx.common.rpc.openapi.dto.GetMainDataReqDto;
import com.mysoft.gfyx.common.rpc.openapi.dto.GetMainDataRespDto;
import com.mysoft.gfyx.common.rpc.openapi.dto.MainDataDto;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientFactoryService;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.getCustomerInfoRequestDto;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.getCustomerInfoResponseDto;
import com.mysoft.gfyx.common.time.TimeService;
import com.mysoft.sdk.context.core.ThreadContextHolder;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：CustomerPool客户池管理服务 业务代码
 *
 * @author JavaSdk generator
 * @date 2022-11-15
 */
@Service
public class CustomerPoolServiceImp extends AppService implements CustomerPoolService {

    @Autowired
    private CustomerPoolDao customerPoolDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private RemoteDeveloperService remoteDeveloperService;

    @Autowired
    private RemoteSupplierService remoteSupplierService;

    @Autowired
    private ContextManager contextManager;

    @Autowired
    private CustomerPoolCloudDataDao customerPoolCloudDataDao;

    @Autowired
    private TimeService timeService;

    @Autowired
    private UserBehaviourService userBehaviourService;

    @Resource
    private MessagePush messagePush;

    @Resource
    private OpenapiClientFactoryService openapiClientFactoryService;
    @Autowired
    private OpptyServiceClientFactoryService opptyServiceClientFactoryService;

    @Autowired
    private MessageInboxService messageInboxService;

    @Autowired
    private NewUserService gfyxUserService;

    @Override
    public CustomerPoolDto selectById(String id) {
        CustomerPool c = customerPoolDao.selectById(id);
        return MappingUtil.getSimpleMapperFacade().map(c, CustomerPoolDto.class);
    }

    @Override
    public CustomerPoolDto getCustomerPool(Map<String, Object> conditions) {

        QueryWrapper queryWrapper = new QueryWrapper();
        conditions.forEach((key, value) -> {
            queryWrapper.eq(key, value);
        });

        queryWrapper.last("limit 1");
        CustomerPool c = customerPoolDao.selectOne(queryWrapper);

        return MappingUtil.getSimpleMapperFacade().map(c, CustomerPoolDto.class);
    }

    @Override
    public CustomerPool addCustomerPool(CustomerPoolDto customerPoolDto) {
        // 当地区没有的时候，调用接口去取地区

        if ((customerPoolDto.getAreaCategoryCode() == null || customerPoolDto.getAreaCategoryCode().length() == 0) || (customerPoolDto.getProvinceCode() == null || customerPoolDto.getProvinceCode().length() == 0)) {

            if (customerPoolDto.getCustomerType() != null && customerPoolDto.getCustomerType().equals("供应商")) {
                GetDataByCreditCodeDto creditCodeBaseRequestDto = new GetDataByCreditCodeDto();
                creditCodeBaseRequestDto.setOrganizing_code(customerPoolDto.getCreditCode());
                Map<String, Object> mainData = remoteSupplierService.getSupplierMainData(creditCodeBaseRequestDto);
                customerPoolDto.setProvinceName(mainData.getOrDefault("province", "").toString());
                customerPoolDto.setProvinceCode(mainData.getOrDefault("province_code", "").toString());
                customerPoolDto.setAreaCategoryName(mainData.getOrDefault("city", "").toString());
                customerPoolDto.setAreaCategoryCode(mainData.getOrDefault("city_code", "").toString());
            } else {
                CreditCodeBaseRequestDto creditCodeBaseRequestDto = new CreditCodeBaseRequestDto();
                creditCodeBaseRequestDto.setCreditCode(customerPoolDto.getCreditCode());
                Map<String, Object> mainData = remoteDeveloperService.getMainData(creditCodeBaseRequestDto);
                customerPoolDto.setProvinceName(mainData.getOrDefault("province", "").toString());
                customerPoolDto.setProvinceCode(mainData.getOrDefault("province_code", "").toString());
                customerPoolDto.setAreaCategoryName(mainData.getOrDefault("city", "").toString());
                customerPoolDto.setAreaCategoryCode(mainData.getOrDefault("city_code", "").toString());
            }

        }

        CustomerPool cEntity = MappingUtil.getSimpleMapperFacade().map(customerPoolDto, CustomerPool.class);
        customerPoolDao.insert(cEntity);
        return cEntity;
    }

    @Override
    public UUID editCustomerPool(CustomerPoolDto customerPoolDto) {
        //转换对象
        CustomerPool customerPoolEntity = MappingUtil.getSimpleMapperFacade().map(customerPoolDto, CustomerPool.class);
        if (customerPoolDto.getCustomerPoolGUID() == null) {
            //插入数据表
            customerPoolDao.insert(customerPoolEntity);
        } else {
            customerPoolDao.updateById(customerPoolEntity);
        }
        return customerPoolEntity.getCustomerPoolGUID();
    }

    @Override
    public CustomerPoolDto getCustomerPoolWithUnique(String CreditCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("CreditCode", CreditCode);
        queryWrapper.eq("__IsDeleted", 0);
        queryWrapper.last("limit 1");
        CustomerPool c = customerPoolDao.selectOne(queryWrapper);
        return MappingUtil.getSimpleMapperFacade().map(c, CustomerPoolDto.class);
    }

    @Override
    public boolean addCustomerPools(Collection<CustomerPoolDto> customerPoolsDto) {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        Collection<String> creditCodes = new ArrayList<>();
        customerPoolsDto.forEach(c -> {
            creditCodes.add(c.getCreditCode());
        });

        if (creditCodes.size() == 0) {
            throw new BusinessLogicException("您尚未选择客户");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("CreditCode", creditCodes);
        queryWrapper.in("__IsDeleted", 0);
        List<CustomerPool> exits = customerPoolDao.selectList(queryWrapper);
        Set<String> exitsCreditCode = new HashSet<>();
        exits.forEach(e -> {
            exitsCreditCode.add(e.getCreditCode());
            //更新cooperationStatus
            customerPoolsDto.forEach(customer -> {
                if (customer.getCreditCode() != null && customer.getCreditCode().equals(e.getCreditCode())) {
                    e.setCooperationStatus(customer.getCooperationStatus());
                }
            });
            customerPoolDao.updateById(e);
        });

        Collection<CustomerPool> customerPools = new ArrayList<>();
        customerPoolsDto.forEach(c -> {
            if (!exitsCreditCode.contains(c.getCreditCode())) {
                customerPools.add(MappingUtil.getSimpleMapperFacade().map(c, CustomerPool.class));
            }

        });
        if (customerPools.size() > 0) {
            customerPoolDao.insertBatchWithDynamicExt(customerPools);
            // 从主档案读取客户的云资料并保存
            Set<String> newCreditCode = new HashSet<>();
            newCreditCode.addAll(creditCodes);
            newCreditCode.removeAll(exitsCreditCode);
            List<String> newCreditCodeList = new ArrayList<>(newCreditCode);
            insertDeveloperCloudData(newCreditCodeList);
        }

        return true;
    }

    @Override
    public List<CustomerPoolDto> addCustomerPoolsByName(List<CustomerPoolDto> customerPoolsDto) {
        Collection<String> companyNameList = new ArrayList<>();
        customerPoolsDto.forEach(c -> {
            companyNameList.add(c.getCustomerName());
        });

        if (companyNameList.size() == 0) {
            throw new BusinessLogicException("您尚未选择客户", PromptType.ALERT);
        }

        // 批量更新
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("CustomerName", companyNameList);
        queryWrapper.in("__IsDeleted", 0);
        List<CustomerPool> exits = customerPoolDao.selectList(queryWrapper);
        Set<String> exitsCompanyNameList = new HashSet<>();
        Set<String> repeatCompanyNameList = new HashSet<>();

        exits.forEach(e -> {
            exitsCompanyNameList.add(e.getCustomerName());
            //更新cooperationStatus
            e = MappingUtil.getSimpleMapperFacade().map(e, CustomerPool.class);
            customerPoolDao.updateById(e);

            // 设置 customer guid 避免查询
            for (int i = 0; i < customerPoolsDto.size(); i++) {
                // customerPoolsDto
                CustomerPoolDto dto = customerPoolsDto.get(i);
                if (Objects.equals(dto.getCustomerName(), e.getCustomerName())) {
                    dto.setCustomerPoolGUID(e.getCustomerPoolGUID());
                    customerPoolsDto.set(i, dto);
                    break;
                }
            }
        });

        // 批量插入
        Collection<CustomerPool> customerPools = new ArrayList<>();
        List<CustomerPoolCloudData> customerPoolCloudDataList = new ArrayList<>();
        customerPoolsDto.forEach(c -> {
            if (!exitsCompanyNameList.contains(c.getCustomerName()) && !repeatCompanyNameList.contains(c.getCustomerName())) {
                c.setCustomerPoolGUID(UUID.randomUUID());
                CustomerPoolCloudData customerPoolCloudData = new CustomerPoolCloudData();
                customerPoolCloudData.setCustomerPoolCloudDataGUID(UUID.randomUUID());
                customerPoolCloudData.setCustomerPoolGUID(c.getCustomerPoolGUID());
                customerPoolCloudData.setCustomerName(c.getCustomerName());
                customerPoolCloudData.setCreditCode(c.getCreditCode());
                customerPoolCloudData.setLatestUpdateTime(new Date());

                // 设置 customer guid 避免查询
                for (int i = 0; i < customerPoolsDto.size(); i++) {
                    // customerPoolsDto
                    CustomerPoolDto dto = customerPoolsDto.get(i);
                    if (Objects.equals(dto.getCustomerName(), c.getCustomerName())) {
                        dto.setCustomerPoolGUID(c.getCustomerPoolGUID());
                        customerPoolsDto.set(i, dto);
                        break;
                    }
                }

                repeatCompanyNameList.add(c.getCustomerName());
                customerPoolCloudDataList.add(customerPoolCloudData);
                customerPools.add(MappingUtil.getSimpleMapperFacade().map(c, CustomerPool.class));
            }

        });
        if (customerPools.size() > 0) {
            customerPoolDao.insertBatchWithDynamicExt(customerPools);
            customerPoolCloudDataDao.insertBatchWithDynamicExt(customerPoolCloudDataList);
        }

        return customerPoolsDto;
    }

    private void insertDeveloperCloudData(List<String> newCreditCodeList) {
        List<Map<String, Object>> developerList = remoteDeveloperService.getLabelMulti(newCreditCodeList);
        HashMap<String, Map<String, Object>> developerMap = new HashMap<>();
        developerList.forEach(d -> {
            developerMap.put(d.get("entity_id").toString(), d);
        });
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("CreditCode", newCreditCodeList);
        List<CustomerPool> exits = customerPoolDao.selectList(queryWrapper);

        List<CustomerPoolCloudData> customerPoolCloudDataList = new ArrayList<>();
        exits.forEach(cp -> {
            Map<String, Object> labelInfo = developerMap.get(cp.getCreditCode());
            if (labelInfo == null) {
                return;
            }
            CustomerPoolCloudData customerPoolCloudData = new CustomerPoolCloudData();
            customerPoolCloudData.setCustomerPoolCloudDataGUID(UUID.randomUUID());
            customerPoolCloudData.setCustomerPoolGUID(cp.getCustomerPoolGUID());
            customerPoolCloudData.setCreditCode(cp.getCreditCode());
            customerPoolCloudData.setCompanyType(labelInfo.get("company_type_label").toString());
            customerPoolCloudData.setDeveloperActivityLabel(labelInfo.get("developer_activity_label").toString());
            customerPoolCloudData.setHighProjectCustomersLabel(labelInfo.get("high_project_customers_label").toString());
            customerPoolCloudData.setIsNewAreaExpandLabel(labelInfo.get("is_new_area_expand_label").toString());
            customerPoolCloudData.setIsNewDecorateExpandLabel(labelInfo.get("is_new_decorate_expand_label").toString());
            customerPoolCloudData.setIsNewLandUsageExpandLabel(labelInfo.get("is_new_land_usage_expand_label").toString());
            customerPoolCloudData.setIsYcgCertification(labelInfo.get("is_ycg_certification").toString());
            customerPoolCloudData.setIsYcgOfflineBusinessConnect(labelInfo.get("is_ycg_offline_business_connect").toString());
            customerPoolCloudData.setLatestUpdateTime(new Date());

            customerPoolCloudDataList.add(customerPoolCloudData);
        });

        if (customerPoolCloudDataList.size() > 0) {
            customerPoolCloudDataDao.insertBatchWithDynamicExt(customerPoolCloudDataList);
        }
    }

    private void updateDeveloperCloudData(List<CustomerPoolCloudData> cloudData, List<String> creditCodes) {
        List<Map<String, Object>> developerList = remoteDeveloperService.getLabelMulti(creditCodes);
        HashMap<String, Map<String, Object>> developerMap = new HashMap<>();
        developerList.forEach(d -> {
            developerMap.put(d.get("entity_id").toString(), d);
        });

        cloudData.forEach(cd -> {
            Map<String, Object> labelInfo = developerMap.get(cd.getCreditCode());
            if (labelInfo == null) {
                return;
            }
            cd.setCompanyType(labelInfo.get("company_type_label").toString());
            cd.setDeveloperActivityLabel(labelInfo.get("developer_activity_label").toString());
            cd.setHighProjectCustomersLabel(labelInfo.get("high_project_customers_label").toString());
            cd.setIsNewAreaExpandLabel(labelInfo.get("is_new_area_expand_label").toString());
            cd.setIsNewDecorateExpandLabel(labelInfo.get("is_new_decorate_expand_label").toString());
            cd.setIsNewLandUsageExpandLabel(labelInfo.get("is_new_land_usage_expand_label").toString());
            cd.setIsYcgCertification(labelInfo.get("is_ycg_certification").toString());
            cd.setIsYcgOfflineBusinessConnect(labelInfo.get("is_ycg_offline_business_connect").toString());
            cd.setLatestUpdateTime(new Date());
        });

        customerPoolCloudDataDao.updateBatchByIdWithDynamicExt(cloudData);
    }

    private void updateDeveloperCloudData(List<CustomerPoolCloudData> cloudData) {
        List<String> creditCodes = new ArrayList<>();
        cloudData.forEach(cd -> creditCodes.add(cd.getCreditCode()));
        updateDeveloperCloudData(cloudData, creditCodes);
    }

    public void updateMainDeveloperData() {
        // 1, 查找没有主档案的客户池表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.isNull("CreditCode");
        queryWrapper.in("__IsDeleted", 0);
        List<CustomerPool> customerPoolList = customerPoolDao.selectList(queryWrapper);
        if (customerPoolList.size() == 0) {
            return;
        }
        // 2, 调用主档案接口，补数据
        List<String> companyNameList = new ArrayList<>();
        OpenapiClientService openapiClientService = openapiClientFactoryService.getOpenapiService();
        customerPoolList.forEach(c -> {
            companyNameList.add(c.getCustomerName());
        });
        GetMainDataReqDto mainReqDto = new GetMainDataReqDto();
        mainReqDto.setDeveloper(companyNameList);
        GetMainDataRespDto mainDataResp = openapiClientService.getMainDataByCompanyName(mainReqDto);
        // 3, 更新客户表数据,更新客户表数据
        customerPoolList.forEach(customerPool -> {
            for (MainDataDto mainDataDto : mainDataResp.getData()) {
                if (Objects.equals(customerPool.getCustomerName(), mainDataDto.getName())) {
                    // 客户池
                    customerPool.setCreditCode(mainDataDto.getCredit_code());
                    customerPool.setAreaCategoryCode(mainDataDto.getCity_code());
                    customerPool.setAreaCategoryName(mainDataDto.getCity());
                    customerPool.setProvinceCode(mainDataDto.getProvince_code());
                    customerPool.setProvinceName(mainDataDto.getProvince());
                    customerPoolDao.updateById(customerPool);
                    // 客户表
                    UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("CustomerPoolGUID", customerPool.getCustomerPoolGUID());
                    Customer customer = new Customer();
                    customer.setCreditCode(mainDataDto.getCredit_code());
                    customer.setAreaCategoryCode(mainDataDto.getCity_code());
                    customer.setAreaCategoryName(mainDataDto.getCity());
                    customer.setProvinceCode(mainDataDto.getProvince_code());
                    customer.setProvinceName(mainDataDto.getProvince());
                    customerDao.update(customer, updateWrapper);
                    break;
                }
            }
        });

    }

    public void scheduleUpdatingCloudData() {
        QueryWrapper<CustomerPool> queryWrapper = new QueryWrapper();
        String timeline = timeService.getPastDate(7, new Date());
        queryWrapper.and(qw -> {
            qw.isNull("CloudDataModifiedTime").or().lt("CloudDataModifiedTime", timeline);
        });

        List<CustomerPool> shouldUpdate = customerPoolDao.selectList(queryWrapper);

        if (shouldUpdate == null || shouldUpdate.size() == 0) {
            System.out.println("没有需要更新的云数据");
            return;
        }

        List<String> creditCodes = new ArrayList<>();
        shouldUpdate.forEach(su -> {
            creditCodes.add(su.getCreditCode());
        });

        // 首先之前线更新一下更新时间
        CustomerPool customerPool = new CustomerPool();
        customerPool.setCloudDataModifiedTime(new Date());
        QueryWrapper<CustomerPool> queryWrapperUpdatingCP = new QueryWrapper();
        queryWrapperUpdatingCP.in("CreditCode", creditCodes);
        customerPoolDao.update(customerPool, queryWrapperUpdatingCP);

        // 首先更新已经存在的
        QueryWrapper<CustomerPoolCloudData> queryWrapperCP = new QueryWrapper();
        queryWrapperCP.in("CreditCode", creditCodes);
        List<CustomerPoolCloudData> exist = customerPoolCloudDataDao.selectList(queryWrapperCP);
        List<String> existCreditCodes = new ArrayList<>();
        exist.forEach(cd -> existCreditCodes.add(cd.getCreditCode()));
        if (exist != null && exist.size() > 0) {
            updateDeveloperCloudData(exist, existCreditCodes);
        }

        // 然后增加还没有的
        Set<String> newCreditCode = new HashSet<>();
        newCreditCode.addAll(creditCodes);
        newCreditCode.removeAll(existCreditCodes);
        List<String> newCreditCodeList = new ArrayList<>(newCreditCode);
        if (newCreditCodeList.size() > 0) {
            insertDeveloperCloudData(newCreditCodeList);
        }
    }

    public void setCooperationStatusByCreditCode(String creditCode) {

    }

    public Set<String> isAdded(List<String> creditCodes) {
        if (creditCodes == null || creditCodes.size() == 0) {
            return new HashSet<>();
        }
        UUID userUUID = contextManager.fetchContextInfo().getUserContext().getUserId();

        QueryWrapper<CustomerPool> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("CreditCode", creditCodes);
        queryWrapper.eq("__IsDeleted", 0);

        List<CustomerPool> customerPool = customerPoolDao.selectList(queryWrapper);
        Set<String> addedList = new HashSet<>();

        customerPool.forEach(c -> {
            addedList.add(c.getCreditCode());
        });

        return addedList;
    }

    public FieldsSetting loadCustomerPoolFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("customerPoolGUID");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "customer-pool";

        fieldsSetting.getFields().add(new DataApiField("customerName", groupName, "客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("creditCode", groupName, "信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("customerPoolGUID", groupName, "主键ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("areaCategoryCode", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("areaCategoryName", groupName, "城市Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("createdTime", groupName, "创建时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("createdName", groupName, "创建人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("provinceCode", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("provinceName", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("assignStatus", groupName, "分配状态", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("customerResponsiblePerson", groupName, "客户负责人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contacterCounts", groupName, "联系方式", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("clueCounts", groupName, "客户线索", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("followTime", groupName, "跟进时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("logo", groupName, "企业logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("tag", groupName, "企业标签", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("developerActivityLabel", groupName, "活跃采购商", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isYcgCertification", groupName, "是否云采购平台认证开发商", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isYcgOfflineBusinessConnect", groupName, "是否云采购平台参加过供需对接会", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("companyLevelTag", groupName, "企业等级", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("companyType", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tagsSet", groupName, "企业标签筛选", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("developerTop100Label", groupName, "地产百强标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewDecorateExpandLabel", groupName, "新精装客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewLandUsageExpandLabel", groupName, "新住宅客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewAreaExpandLabel", groupName, "新区域拓展标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("highProjectCustomersLabel", groupName, "高端项目客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("source", groupName, "客户来源", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("CustomerType", groupName, "客户类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_score", groupName, "好客户得分", FieldType.Int));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadCustomerPoolData(LoadDataParams options) {
        // 分页
        optionsProcess(options);
        CustomersPoolRequestDto dto = new CustomersPoolRequestDto();

        dto.setPage(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        dto.setOffset(options.getPageIndex() * dto.getPageSize());
        if (options.getPageIndex() == -1) {//如果是导出全部数据，pageIndex=-1，此时不做limit操作
            dto.setIsNeedLimit(0);
        }
        //获取客户池数据
        CustomerPoolTotalDto total = customerPoolDao.queryCustomerPoolTotal(dto);
        List<CustomerPoolDataDto> res = customerPoolDao.queryCustomerPoolData(dto);
        if (res == null || res.size() == 0) {
            ListDataResult result = new ListDataResult();
            result.setData(res);
            result.setTotal(0);
            return result;
        }
        List<String> creditCodeList = new ArrayList<>();
        res.forEach(o -> {
            creditCodeList.add(o.getCreditCode());
        });

        getCustomerInfoRequestDto customerInfoRequestDto = new getCustomerInfoRequestDto();
        customerInfoRequestDto.setOrganizing_code_list(creditCodeList);
        OpptyServiceClientService opptyService = opptyServiceClientFactoryService.getOpptyServiceClientService();
        getCustomerInfoResponseDto customerInfoResp = opptyService.getCustomerInfo(customerInfoRequestDto);

        if (customerInfoResp != null && customerInfoResp.getData() != null) {
            customerInfoResp.getData().forEach(d -> {
                res.forEach(r -> {
                    r.setLogo(d.getLogo());
                    r.setTag(d.getTags());
                    r.setDeveloper_score(d.getScore());
                });
            });
        }
//        //获取主档案开发商
//        List<Map<String, Object>> developerList = remoteDeveloperService.getMainDataMulti(creditCodeList);
//        res.forEach(r -> {
//            developerList.forEach(d -> {
//                for (String key : d.keySet()) {
//                    if (key.equals(r.getCreditCode())) {
//                        Object value = d.get(key);
//                        Map map = (Map) value;
//                        r.setLogo(map.get("logo").toString());
//                        r.setTag(map.get("tag").toString());
//                        if (map.get("developer_score") != null) {
//                            Integer developerScore = (Integer) map.get("developer_score");
//                            r.setDeveloper_score(developerScore);
//                        } else {
//                            r.setDeveloper_score(null);
//                        }
//                    }
//                }
//            });
//        });
        // 获取采购商得分
        ListDataResult result = new ListDataResult();
        result.setData(res);
        result.setTotal(total.getTotal());
        return result;
    }

    protected void optionsProcess(LoadDataParams options) {
        options.getOptions().getFilters().forEach(f -> {
            f.getCondition().forEach(c -> {
                /*if (c.getField().equals("cityCode")) {
                    c.setOperatorType("like");
                    c.setValue("[" + c.getValue() + "]");
                }
                if (c.getField().equals("provinceCode")) {
                    c.setOperatorType("like");
                    c.setValue("[" + c.getValue() + "]");
                }*/

            });
        });
    }

    public void deleteCustomerPool(DeleteByIdRequestDto dto) {
        //删除客户池
        CustomerPool c = customerPoolDao.selectById(dto.getId());
        c.set__IsDeleted(1);
        customerPoolDao.updateById(c);

        //发送站内信
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CustomerPoolGUID", dto.getId());
        queryWrapper.eq("__IsDeleted", 0);
        List<Customer> customerList = customerDao.selectList(queryWrapper);
        customerList.forEach(cu -> {
            MessagePushDTO puchDto = new MessagePushDTO();
            puchDto.setUserGuid(cu.getCustomerResponsiblePersonGUID());
            puchDto.setWakeType("(。・・)ノ");
            puchDto.setWakeSubject("尊敬的用户，您负责的【" + cu.getCustomerName() + "】已被删除。");
            puchDto.setPageUrl("/std/40220902/08daf483-0f12-45a2-828e-f4b066fa28f7");
            puchDto.setAppCode("4022");
            puchDto.setBusinessGuid(UUID.randomUUID());
            puchDto.setBusinessType("客户变动");
            messagePush.sendToDo(puchDto);

            MessageInboxDto messageDto = new MessageInboxDto();
            messageDto.setTitle("客户变动通知");
            messageDto.setMessageType("客户变动");
            messageDto.setContent(puchDto.getWakeSubject());
            messageDto.setLink(puchDto.getPageUrl());
            messageDto.setSenderId(gfyxUserService.GetAdminId());
            messageDto.setReceiverId(gfyxUserService.GetUserId(puchDto.getUserGuid().toString()));
            messageInboxService.AddMessage(messageDto);
        });

        //删除客户表
        Customer customer = new Customer();
        customer.set__IsDeleted(1);
        QueryWrapper<Customer> queryWrapperUpdate = new QueryWrapper<>();
        queryWrapperUpdate.eq("CustomerPoolGUID", dto.getId());
        queryWrapperUpdate.eq("__IsDeleted", 0);
        customerDao.update(customer, queryWrapperUpdate);

        //记录操作日志
        userBehaviourService.addUserBehaviour("客户池", "", "删除客户池", "删除了客户池里的【" + c.getCustomerName() + "】");
    }

}